import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

/**
 * 开启端口，监听UDP，收到客户端发送的包，返回当前自己的ip
 */
public class MulticastListener extends Thread {

	public interface ClientListener {
		public void getClient(String clientIp);
	}

	ClientListener listener;
	private int port;
	private String host;

	public MulticastListener(ClientListener listener)
			throws UnknownHostException {
		this.host = Config.BROADCAST_IP;
		// this.host = address.getHostAddress();
		this.port = Config.BROADCAST_PORT;
		this.listener = listener;
	}

	@Override
	public void run() {
		super.run();
		listen();
	}

	/**
	 * 监听组播端口
	 */
	public void listen() {
		byte[] data = new byte[256];
		InetAddress ip = null;
		try {
			ip = InetAddress.getByName(this.host);
			MulticastSocket ms = new MulticastSocket(this.port);
			ms.joinGroup(ip);
			DatagramPacket packet = new DatagramPacket(data, data.length);
			// receive()是阻塞方法，会等待客户端发送过来的信息
			ms.receive(packet);
			// 收到广播后，得到发广播的地址
			String clientIp = packet.getAddress().getHostAddress();
			Log.d("get client ip=" + clientIp);
			String message = new String(packet.getData(), 0, packet.getLength());
			Log.d("get client data=" + message);
			ms.leaveGroup(ip);
			ms.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
